﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
public partial class Manage_basisset_ClassType : AdminPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CheckAdmin();
        GetUserPermisions();
        if (!IsPostBack)
        {

            // 正确的属性设置方法
            this.GridView1.Attributes.Add("SortExpression", "ClassTypeId");
            this.GridView1.Attributes.Add("SortDirection", "ASC");
            DataTable dt = new DataTable();
            dt.Columns.Add("ClassTypeId");
            dt.Columns.Add("Name");
            dt.Columns.Add("");

            GridviewControl.GridViewDataBind(this.GridView1, dt);
            GridviewControl.ResetGridView(this.GridView1);

           // GridViewBind();
            if (add == 1)
            {
                addClassType.Enabled = true;
                fuExcel.Enabled = true;
                btnInput.Enabled = true;
            }
            else
            {
                addClassType.Enabled = false;
                fuExcel.Enabled = false;
                btnInput.Enabled = false;
            }
           
            tbladdClassType.Style.Remove("display");
            tbladdClassType.Style.Add("display", "none");
        }
    }
    protected void CheckAdmin()
    {
        if (AdminSessionHelper.UserDetails == null)
        {
            JsHelper.TopAlertRedirect("请先登录", "../login.aspx", this.Page);
        }
    }
    protected void GridViewBind()
    {
       
        // 获取GridView排序数据列及排序方向
        string sortExpression = this.GridView1.Attributes["SortExpression"];
        string sortDirection = this.GridView1.Attributes["SortDirection"];

        string keyword = txtkeyword.Text.Trim();
        if (CoreTools.ProcessSqlStr(keyword, 0))
        {
            DataSet ds = jtDataAccess.SearchClassType(keyword, pager1.PageSize, pager1.CurrentPageIndex, sortExpression, sortDirection);
            if (CoreTools.CheckDataSet(ds))
            {
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }

                // GridView绑定并显示数据
               
                GridviewControl.GridViewDataBind(this.GridView1, ds.Tables[0]);

               // this.GridView1.DataSource = ds.Tables[0];
               // this.GridView1.DataBind();
                pager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0]["qty"]);

                if (delete == 1)
                {
                    btnDeleteMass.Enabled = true;
                    selectAll.Enabled = true;
                }
                else
                {
                    btnDeleteMass.Enabled = false;
                    selectAll.Enabled = false;
                }
            }
            else
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ClassTypeId;");
                dt.Columns.Add("Name");
                dt.Columns.Add("");

                GridviewControl.GridViewDataBind(this.GridView1, dt);
                pager1.RecordCount = 0;
                btnDeleteMass.Enabled = false;
                selectAll.Enabled = false;
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
            txtkeyword.Focus();
        }

    }
    protected void pager1_PageChanged(object sender, EventArgs e)
    {
        GridView1.EditIndex = -1;
        GridViewBind();
    }
    protected void btnDeleteMass_Click(object sender, EventArgs e)
    {
        UserType ut = new UserType();//用户自定义类型
        DataTable ClassType = ut.GetClassTypeTableType();

        DataRow ClassTypeRow;
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("chkID");
            HiddenField hdfClassTypeId = (HiddenField)GridView1.Rows[i].FindControl("hdfClassTypeId");
            if (cbox.Checked == true && hdfClassTypeId != null && hdfClassTypeId.Value != "")
            {

                ClassTypeRow = ClassType.NewRow();
                ClassTypeRow["ClassTypeId"] = hdfClassTypeId.Value;
                ClassType.Rows.Add(ClassTypeRow);
            }
        }
        ClassType.AcceptChanges();
        int flag = jtDataAccess.BatchDelClassType(ClassType);

        switch (flag)
        {
            case -1:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("该课程类型已经使用，不允许删除！"), false);
                break;
            case 0:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除失败！"), false);
                break;

            case 1:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除成功！"), false);
                GridViewBind();
                break;

            default:
                break;
        }
        selectAll.Checked = false;

    }


    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //首先判断是否是数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //当鼠标停留时更改背景色
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FCFDEE'");
            //当鼠标移开时还原背景色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            LinkButton BtnDelete = (LinkButton)e.Row.Cells[2].Controls[2];
            if (BtnDelete.Text == "删除")
            {
                ((LinkButton)e.Row.Cells[2].Controls[2]).Attributes.Add("onclick", "javascript:return confirm('您确定要删除该记录吗？')");
            }
        }
        if (edit == 1)
            ((CommandField)GridView1.Columns[2]).ShowEditButton = true;
        else
            ((CommandField)GridView1.Columns[2]).ShowEditButton = false;
        if (delete == 1)
            ((CommandField)GridView1.Columns[2]).ShowDeleteButton = true;
        else
            ((CommandField)GridView1.Columns[2]).ShowDeleteButton = false;
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        GridViewBind();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        GridViewBind();
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        int flag = 0;
        int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
        TextBox  txtname=(TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
        string name =txtname.Text;
        name = name.Trim();
        if (name == "")
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("课程类型名称不能为空！"), false);
            txtname.Focus();
        }
        else  if (CoreTools.ProcessSqlStr(name, 0))
        {
            flag = jtDataAccess.OpClassType(JTDataAccess.OpType.Update, id, name);

            switch (flag)
            {
                case -1:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("该课程类型已经存在，添加失败！"), false);
                    break;
                case 0:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("操作失败，请重试！"), false);
                    break;
                default:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("操作成功！"), false);

                    break;
            }
            GridView1.EditIndex = -1;
            GridViewBind();
        }
        else
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
            txtname.Focus();
        }
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        int flag = 0;
        int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
        string name = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblName")).Text;
        flag = jtDataAccess.OpClassType(JTDataAccess.OpType.Delete, id, name);

        switch (flag)
        {

            case -1:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("该课程类型已经在使用，不允许删除！"), false);
                break;
            case 0:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除失败！"), false);
                break;
            default:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除成功！"), false);
                break;
        }
        GridView1.EditIndex = -1;
        GridViewBind();


    }
    protected void addClassType_Click(object sender, EventArgs e)
    {
        tbladdClassType.Style.Remove("display");
        tbladdClassType.Style.Add("display", "block");
        txtname.Text = "";
      if (GridView1.Rows.Count == 1 &&GridView1.Rows[0].Cells[0].Text == GridviewControl.EmptyText)
      {
          DataTable dt = new DataTable();
          dt.Columns.Add("ClassTypeId");
          dt.Columns.Add("Name");
          dt.Columns.Add("");

          GridviewControl.GridViewDataBind(this.GridView1, dt);
      }
        
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string name = txtname.Text.Trim();
        if (CoreTools.ProcessSqlStr(name, 0))
        {
            int flag = jtDataAccess.OpClassType(JTDataAccess.OpType.Insert, 0, name);
            switch (flag)
            {
                case -1:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("该课程类型已存在,添加失败！"), false);
                    break;
                case 0:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("添加失败，请重试！"), false);
                    break;
                default:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("添加成功！"), false);
                    GridViewBind();
                    tbladdClassType.Style.Remove("display");
                    tbladdClassType.Style.Add("display", "none");
                    break;
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
            txtname.Focus();
        }
    }

    protected void selectAll_CheckedChanged(object sender, EventArgs e)
    {
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("chkID");
            if (selectAll.Checked == true)
            {
                cbox.Checked = true;
            }
            else
            {
                cbox.Checked = false;
            }
        }

    }
    protected void btnInput_Click(object sender, EventArgs e)
    {
        try
        {
            if (fuExcel.HasFile)
            {
                string fileType = fuExcel.FileName.Substring(fuExcel.FileName.LastIndexOf(".") + 1).ToUpper();

                if (fileType == "XLS" || fileType == "XLSX")
                {
                    DataTable dt = jtDataAccess.readExcelDataFromClient(fuExcel, "Sheet1", "Sheet1");
                    UserType ut = new UserType();//用户自定义类型
                    DataTable classType = ut.GetClassTypeTableType();
                    DataRow classTypeRow;

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            classTypeRow = classType.NewRow();

                            classTypeRow["NAME"] = row["课程类型"];
                            classType.Rows.Add(classTypeRow);
                        }
                    }

                    classType.AcceptChanges();
                    int flag = jtDataAccess.ImportClassType(classType);

                    switch (flag)
                    {
                        case -1:
                            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("Excel文件中课程类型名称有重复！"), false);
                            break;
                        case 0:
                            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("没有导入任何记录，请检查Excel文件！"), false);
                            break;
                        default:
                            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(string.Format("成功导入{0}条记录", flag)), false);
                            GridViewBind();
                            break;
                    }
                }

            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    protected void ibtnsearch_Click(object sender, ImageClickEventArgs e)
    {
        GridView1.EditIndex = -1;
        GridViewBind();
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        // 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();

        // 假定为排序方向为“顺序”
        string sortDirection = "ASC";

        // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
        if (sortExpression == this.GridView1.Attributes["SortExpression"])
        {
            //获得下一次的排序状态
            sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
        }

        // 重新设定GridView排序数据列及排序方向
        this.GridView1.Attributes["SortExpression"] = sortExpression;
        this.GridView1.Attributes["SortDirection"] = sortDirection;

        this.GridViewBind();
    }



    protected void btnexport_Click(object sender, EventArgs e)
    {
        DataTable dt = GetExportData();
        ExcelExport(GetStringWriter(dt), "课程类型.xls"); 

    }
    protected DataTable GetExportData()
    {
        DataTable dt=new DataTable();
        // 获取GridView排序数据列及排序方向
        string sortExpression = this.GridView1.Attributes["SortExpression"];
        string sortDirection = this.GridView1.Attributes["SortDirection"];

        string keyword = txtkeyword.Text.Trim();
        if (CoreTools.ProcessSqlStr(keyword, 0))
        {
            DataSet ds = jtDataAccess.SearchClassType(keyword, pager1.PageSize, 0, sortExpression, sortDirection);
            if (CoreTools.CheckDataSet(ds))
            {
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }
                dt = ds.Tables[0];

            }
        }
        return dt;

    }
    protected void ExcelExport(StringWriter sw, string exportFileName)
    {
      
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.Charset = "GB2312";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(exportFileName, System.Text.Encoding.GetEncoding("utf-8")));
        HttpContext.Current.Response.ContentType = "application/ms-excel";
       // HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\" />");
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End(); 


    }
    //将datatable中的数据进行组装，比如添加列头（这样excel文件中第一行就看到列头名称） 
    public static StringWriter GetStringWriter(DataTable dt)
    {
        StringWriter sw = new StringWriter();

        //先写列的表头，这样保证如果没有数据也能输出列表头 
        sw.Write("类型名称" + "\t ");
        sw.Write(sw.NewLine);

        //如果包含数据 
        if (dt != null)
        {
            //写数据 
            foreach (DataRow dr in dt.Rows)
            {
               
                sw.Write(dr["Name"].ToString() + "\t ");
                //换行 
                sw.Write(sw.NewLine);
            }
        }
        sw.Close();
        return sw;
    } 


}